from ninja import Router, Form, Schema

router = Router()


#   Form(...) 表示取 x-www-form-urlencoded 中的数据
@router.post('/login')
def login(request,username: str = Form(...),password:str = Form(...)):
    return  {'username': username, 'password': password}

class Item(Schema):
    name: str
    # 前端不传递体中的这个key, 默认none
    # 前端传递体中的这个key, 不给值，就是''
    description: str = None
    price: float
    quantity: int

# 表单定义字段
@router.post('/items')
def items(request,item:Item=Form(...)):
    print(item)
    return item


# 前端传递 blank, name=123&description=&price=1&quantity=55555'
# 我们给 description= 这样的默认值。上面就识别为空了
from typing import Generic, TypeVar
PydanticField = TypeVar("PydanticField")
from pydantic.fields import ModelField
class EmptyStrToDefault(Generic[PydanticField]):
    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, value: PydanticField, field: ModelField) -> PydanticField:
        if value == "":
            return field.default
        return value


class Item2(Schema):
    name: str
    description: EmptyStrToDefault[str] = 'test desc'
    price: EmptyStrToDefault[float] = 0.0
    quantity: EmptyStrToDefault[int] = 0
    in_stock: EmptyStrToDefault[bool] = True

@router.post("/items-blank-default")
def update(request, item: Item2=Form(...)):
    return item.dict()
